package com.yx.framedemo.view.viewblock.gesturelock.gesture;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.yx.framedemo.R;
import com.yx.framedemo.view.main.MainActivity;
import com.yx.framedemo.view.main.ProxyApplication;
import com.yx.framedemo.view.viewblock.gesturelock.util.AnimationUtil;
import com.yx.framedemo.view.viewblock.gesturelock.view.LockPatternUtils;
import com.yx.framedemo.view.viewblock.gesturelock.view.LockPatternView;

import java.util.List;


/**
 * 解锁登录(已有手势密码时的界面)
 */
@SuppressLint("ResourceAsColor")
public class UnlockGesturePasswordActivity extends AppCompatActivity {
    private LockPatternView mLockPatternView;
    private int mFailedPatternAttemptsSinceLastTimeout = 0;
    private CountDownTimer mCountdownTimer = null;
    private Animation mShakeAnim;
    private Context context;

    private TextView unlock_text, mTextView, to_pwdloding, to_phoneupdate;
    private String phone;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gesturepassword_unlock);
        context = this;
        //  ViewUtils.inject(this);
        unlock_text = (TextView) findViewById(R.id.gesturepwd_unlock_text);
        mTextView = (TextView) findViewById(R.id.gesturepwd_unlock_failtip);
        to_pwdloding = (TextView) findViewById(R.id.to_pwdloding); //  使用密码登录
        to_pwdloding.setOnClickListener(clicks);
        to_phoneupdate = (TextView) findViewById(R.id.to_phoneupdate); //  切换其他账号
        to_phoneupdate.setOnClickListener(clicks);
        mLockPatternView = (LockPatternView) findViewById(R.id.gesturepwd_unlock_lockview);
        mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
        mLockPatternView.setTactileFeedbackEnabled(true);
        mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.gesture_shake_x);
        SharedPreferences sp = this.getSharedPreferences("userPhone", Context.MODE_PRIVATE);
        phone = sp.getString("phone", "");
        if (!phone.equals("")) {
            String a = phone.substring(0, 3);
            String b = phone.substring(phone.length() - 4, phone.length());
            unlock_text.setText(a + " **** " + b);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCountdownTimer != null)
            mCountdownTimer.cancel();
    }

    private Runnable mClearPatternRunnable = new Runnable() {
        public void run() {
            mLockPatternView.clearPattern();
        }
    };

    protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() {

        @Override
        public void onPatternStart() {
            //   TODO Auto-generated method stub
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
            patternInProgress();
        }

        public void onPatternDetected(List<LockPatternView.Cell> pattern) {
            //   TODO Auto-generated method stub
            if (pattern == null)
                return;
            if (ProxyApplication.getInstance().getLockPatternUtils()
                    .checkPattern(pattern)) { //   解锁成功
                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Correct);

                //   解锁成功返回需要用户信息的页面----
                loginSuccessToMainAcrtivity();
            } else { //   解锁失败-----重新登录
                mLockPatternView.setDisplayMode(LockPatternView.DisplayMode.Wrong);

                if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) {

                    mFailedPatternAttemptsSinceLastTimeout++;
                    int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT
                            - mFailedPatternAttemptsSinceLastTimeout;
                    if (retry > 0) {
                        //  changeUser.setVisibility(View.VISIBLE);
                        if (retry == 0)
                            Toast.makeText(UnlockGesturePasswordActivity.this, UnlockGesturePasswordActivity.this
                                    .getString(R.string.toastlock), Toast.LENGTH_SHORT).show();

                        mTextView.setText("密码错误，还可以再输入" + retry + "次");
                        mTextView.setTextColor(Color.parseColor("#f09636"));
                        mTextView.startAnimation(mShakeAnim);
                    } else {
                        //   疯狂输入手势密码次数用完后：清空手势密码，清空本地文件，状态改为未登录
                        //   delete
                        //   清除 手势文件
                        ProxyApplication.getInstance().getLockPatternUtils().clearLock();
                    }
                } else {
                    Toast.makeText(UnlockGesturePasswordActivity.this, "输入长度不够，请重试", Toast.LENGTH_SHORT).show();
                }
                mLockPatternView.clearPattern();
            }
        }

        @Override
        public void onPatternCleared() {
            //   TODO Auto-generated method stub
            mLockPatternView.removeCallbacks(mClearPatternRunnable);
        }

        private void patternInProgress() {
        }

        @Override
        public void onPatternCellAdded(List<LockPatternView.Cell> pattern) {
            //   TODO Auto-generated method stub

        }


    };

    /**
     * 登录成功,打开主页
     */
    private void loginSuccessToMainAcrtivity() {
        Intent intent = new Intent(context, MainActivity.class);
        context.startActivity(intent);
        finish();
        AnimationUtil.finishActivityAnimation(UnlockGesturePasswordActivity.this); //  关闭
    }


    private OnClickListener clicks = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent2;
            switch (v.getId()) {
                case R.id.to_pwdloding: //  密码登录
                    //  关闭当前手势密码界面
                    AnimationUtil.finishActivityAnimation(context);
                    break;
                case R.id.to_phoneupdate: //  切换其他账号
                    //  关闭当前手势密码界面
                    AnimationUtil.finishActivityAnimation(context);
                    break;
            }

        }
    };


    Runnable attemptLockout = new Runnable() {

        @Override
        public void run() {
            mLockPatternView.clearPattern();
            mLockPatternView.setEnabled(false);
            mCountdownTimer = new CountDownTimer(
                    LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) {

                @Override
                public void onTick(long millisUntilFinished) {
                    int secondsRemaining = (int) (millisUntilFinished / 1000) - 1;
                    if (secondsRemaining > 0) {
                        mTextView.setText(secondsRemaining + " 秒后重试");
                    } else {
                        mTextView.setText(UnlockGesturePasswordActivity.this
                                .getString(R.string.gesture_drawPwd));
                        mTextView.setTextColor(Color.WHITE);
                    }

                }

                @Override
                public void onFinish() {
                    mLockPatternView.setEnabled(true);
                    mFailedPatternAttemptsSinceLastTimeout = 0;
                }
            }.start();
        }
    };


}
